package admin;

import com.fasterxml.jackson.databind.ObjectMapper;
import util.DBUtil;
import util.uploadAvatarUtil;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;
import java.util.UUID;

@WebServlet("/adminInfoServlet")
@MultipartConfig
public class adminInfoServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        
        String action = request.getParameter("action");
        HttpSession session = request.getSession();
        String adminUsername = (String) session.getAttribute("adminUsername");

        if (adminUsername == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            out.print(mapper.writeValueAsString(Map.of("status", "error", "message", "未登录")));
            return;
        }

        try (Connection conn = DBUtil.getConnection()) {
            switch (action) {
                case "updateAvatar":
                    Part filePart = request.getPart("avatar");
                    String fileName = UUID.randomUUID().toString() + getFileExtension(filePart);
                    
                    uploadAvatarUtil uploadUtil = new uploadAvatarUtil();
                    String avatarUrl = uploadUtil.adminUploadFile(fileName, filePart.getInputStream());

                    try (PreparedStatement stmt = conn.prepareStatement(
                            "UPDATE admin SET avatarUrl = ? WHERE username = ?")) {
                        stmt.setString(1, avatarUrl);
                        stmt.setString(2, adminUsername);
                        stmt.executeUpdate();
                        
                        // 更新session中的头像URL
                        session.setAttribute("adminAvatarUrl", avatarUrl);
                        
                        // 确保返回完整的URL
                        out.print(mapper.writeValueAsString(Map.of(
                            "status", "success",
                            "avatarUrl", avatarUrl
                        )));
                    }
                    break;

                case "updateProfile":
                    String newUsername = request.getParameter("newUsername");
                    String email = request.getParameter("email");
                    
                    // 检查用户名是否已存在
                    if (!newUsername.equals(adminUsername)) {
                        try (PreparedStatement checkStmt = conn.prepareStatement(
                                "SELECT id FROM admin WHERE username = ?")) {
                            checkStmt.setString(1, newUsername);
                            if (checkStmt.executeQuery().next()) {
                                out.print(mapper.writeValueAsString(Map.of(
                                    "status", "error",
                                    "message", "用户名已存在"
                                )));
                                return;
                            }
                        }
                    }

                    // 更新个人信息
                    try (PreparedStatement stmt = conn.prepareStatement(
                            "UPDATE admin SET username = ?, email = ? WHERE username = ?")) {
                        stmt.setString(1, newUsername);
                        stmt.setString(2, email);
                        stmt.setString(3, adminUsername);
                        stmt.executeUpdate();
                        
                        // 更新session
                        session.setAttribute("adminUsername", newUsername);
                        
                        out.print(mapper.writeValueAsString(Map.of("status", "success")));
                    }
                    break;

                case "updatePassword":
                    String oldPassword = request.getParameter("oldPassword");
                    String newPassword = request.getParameter("newPassword");

                    // 验证旧密码
                    try (PreparedStatement stmt = conn.prepareStatement(
                            "SELECT id FROM admin WHERE username = ? AND password = ?")) {
                        stmt.setString(1, adminUsername);
                        stmt.setString(2, oldPassword);
                        ResultSet rs = stmt.executeQuery();
                        
                        if (rs.next()) {
                            // 更新密码
                            try (PreparedStatement updateStmt = conn.prepareStatement(
                                    "UPDATE admin SET password = ? WHERE username = ?")) {
                                updateStmt.setString(1, newPassword);
                                updateStmt.setString(2, adminUsername);
                                updateStmt.executeUpdate();
                                out.print(mapper.writeValueAsString(Map.of("status", "success")));
                            }
                        } else {
                            out.print(mapper.writeValueAsString(Map.of("status", "error", "message", "原密码错误")));
                        }
                    }
                    break;

                case "logout":
                    session.invalidate();
                    out.print(mapper.writeValueAsString(Map.of("status", "success")));
                    break;

                default:
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    out.print(mapper.writeValueAsString(Map.of("status", "error", "message", "无效操作")));
            }
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.print(mapper.writeValueAsString(Map.of(
                "status", "error", 
                "message", e.getMessage()
            )));
        }
    }

    private String getFileExtension(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] tokens = contentDisp.split(";");
        for (String token : tokens) {
            if (token.trim().startsWith("filename")) {
                String fileName = token.substring(token.indexOf("=") + 2, token.length() - 1);
                return fileName.substring(fileName.lastIndexOf("."));
            }
        }
        return "";
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doPost(request, response);
    }
}
